package com.dianrui.agent.update;


import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;

import com.dianrui.agent.util.ToastUtil;
import com.xuexiang.xupdate.proxy.IUpdateHttpService;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;

;


public class OKHttpUpdateHttpService implements IUpdateHttpService {
    private boolean mIsPostJson;
    private Handler handler;



    public OKHttpUpdateHttpService() {
        this(false);
        handler = new Handler(Looper.getMainLooper());

    }

    public OKHttpUpdateHttpService(boolean isPostJson) {
        mIsPostJson = isPostJson;
    }


    @Override
    public void asyncGet(@NonNull final String url, @NonNull Map<String, Object> params, final @NonNull Callback callBack) {
        OkHttpUtils.get().url(url).tag(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("TAG", "请求失败=" + e.getMessage());
                ToastUtil.showToast( e.getMessage());
                call.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    callBack.onSuccess(response);
                    Log.e("服务器返回数据---->", "====================================网络请求[" + "],请求日志如下===================================" +
                            "\n\n请求地址:" + url +
                            "\n\n请求数据响应代码:" + id + "" +
                            "\n\n服务器返回的数据>" + response);
                } else {

                }
            }
        });
    }

    @Override
    public void asyncPost(@NonNull String url, @NonNull Map<String, Object> params, final @NonNull Callback callBack) {

    }

    @Override
    public void download(@NonNull final String url, @NonNull String path, @NonNull String fileName, final @NonNull DownloadCallback callback) {
        OkHttpUtils.get().url(url).tag(url).build().execute(new FileCallBack(path, fileName) {
            @Override
            public void inProgress(float progress, long total, int id) {
                callback.onProgress(progress, total);

            }

            @Override
            public void onError(Call call, Exception e, int id) {
                callback.onError(e);

            }

            @Override
            public void onResponse(File response, int id) {
                callback.onSuccess(response);
            }

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                callback.onStart();
            }
        });

    }

    @Override
    public void cancelDownload(@NonNull String url) {

    }


}
